﻿using System;
using System.Net;
using AgentListener.Model.Network;
using AgentListener.Mongo;
using Common;
using Common.Configuration;
using Common.Annotations;
using NLog;

namespace AgentListener.Controllers.Strategies
{
    internal class GetMetricsStrategy : IRequestStrategy
    {
        private readonly IMongoProvider _provider;
        private static readonly Logger NLog = LogManager.GetCurrentClassLogger();

        public GetMetricsStrategy([NotNull] IMongoProvider provider)
        {
            if (provider == null) throw new ArgumentNullException("provider");
            _provider = provider;
        }

        public ResponseInfo Process(RequestInfo data)
        {
            var metricsData = JsonConvertWrapper.Deserialize<MetricsData>(data.Query);

            NLog.Trace(data.Query);

            if(metricsData != null)
            {
                NLog.Trace("MetricsData: agentId={0}; isNew={1}", metricsData.AgentId, metricsData.ShowNew);
                var agent = _provider.GetAgent(metricsData.AgentId);

                if(agent == null)
                    return new ResponseInfo(HttpStatusCode.InternalServerError, "Agent not found");

                if(metricsData.ShowNew)
                    return new ResponseInfo(HttpStatusCode.InternalServerError, "New metrics not implemented");

                var metrics = JsonConvertWrapper.Serialize(agent.Metrics);
                return new ResponseInfo(HttpStatusCode.OK, metrics);
            }

            return new ResponseInfo(HttpStatusCode.InternalServerError, "Wrong json message format");
        }
    }
}